package com.hujing;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author : hujing
 * @Date: 2025/7/28 9:57
 * @Description:线程安全例子，通过ReentrantLock实现线程安全
 */
public class ThreadDemo1 {
    
    private static int sum = 0;
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        // 创建线程1
        Thread t1 = new Thread(ThreadDemo1::add);
        // 创建线程2
        Thread t2 = new Thread(ThreadDemo1::subtract);
        
        // 启动线程
        t1.start();
        t2.start();
        
        // 等待线程执行完
        try{
            t1.join();
            t2.join();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        
        // 输出结果
        System.out.println("sum = " + sum);
    }
    
    // 对sum进行加操作
    public static void add(){
        lock.lock();
        try{
            for(int i = 0;i< 10000;i++){
                sum += i;
            }
        }finally{
            lock.unlock();
        }
    }
    
    // 对sum进行减操作
    public static void subtract(){
        lock.lock();
        try{
            for(int i = 0;i< 10000;i++){
                sum -= i;
            }
        }finally{
            lock.unlock();
        }
    }
    
}
